package com.huidu.bitrade.controller.common;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectResult;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Date;

/**
 * 生产环境无sts账号上传，生成临时访问path
 */
public class UploadControllerTestUrl {

    private OSSClient client = null;
    private String accessKeyId = "LTAI5tMiQZ1tJrC1WsE7tgCc";
    private String accessKeySecret = "tQ0a45EmsXxrN695vo6iByl6Jgfpxj";
    private String endpoint = "oss-cn-hongkong.aliyuncs.com";
    private String bucketName = "test-primary-123";


    public OSSClient initClient() {
        if (null == client) {
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(5000);
            conf.setMaxErrorRetry(10);
            CredentialsProvider provider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
            client = new OSSClient(endpoint, provider, conf);
        }
        return client;
    }

    public String getUrl(String key) {
        initClient();
        // 设置URL过期时间。
        Date expiration = new Date(new Date().getTime() + 20 * 1000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = client.generatePresignedUrl(bucketName, key, expiration);
        return url.toString();
    }


    @Test
    public void uploadOssImage1() throws FileNotFoundException {
        OSSClient ossClient = new OSSClient(endpoint,
                accessKeyId,
                accessKeySecret);
        String ossPath = "test.jpg";
        File file = new File("C:\\Users\\a\\Desktop\\微信图片_20230616090558.jpg");
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, ossPath, new FileInputStream(file));
        String string = putObjectResult.toString();
        System.out.println(string);

        initClient();
        String url = getUrl(ossPath);
        System.out.println(url);
    }
}
